package tsinghua.smxq.mc;


import java.io.IOException;
import java.net.URL;

import tsinghua.smxq.foodprice.FoodandFoodId;
import tsinghua.smxq.foodprice.GraphView.GraphViewData;
import tsinghua.smxq.foodprice.GraphView.GraphViewSeries;
import tsinghua.smxq.foodprice.HttpConnection;
import tsinghua.smxq.foodprice.LineGraphView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;

/*
 * 功能：显示对应市场、菜最近几天的价格变化折线图 
 */
public class FoodPriceLineChartActivity extends Activity {

	GraphViewSeries gvs;	
	GraphViewData[] gvd;
	String city,food;
	int cityId,foodId;
	URL url;
	String operationResult = "failure";
	String [] foodprices;
	private Toast toast;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		city = getIntent().getStringExtra("city");
		cityId = getIntent().getIntExtra("cityId", 0);
		food = getIntent().getStringExtra("food");		
		foodId = getIntent().getIntExtra("foodId", 0);
		//连接服务器
		
		try {
			url = new URL("http://"+Constants.serverIP+":8080/MobileCityServer/queryLastFivePrices.do?" 
										+"cityId="+cityId
										+"&foodId="+foodId);
			operationResult = HttpConnection.httpConnection(url);
			if(operationResult.compareToIgnoreCase("failure")==0)
  			{
  				DisplayToast("菜价查询失败，请查看网络是否正常",Toast.LENGTH_SHORT);
  				Intent gotoIntent = new Intent(FoodPriceLineChartActivity.this, FoodPriceRequestActivity.class);            		                		
	  			FoodPriceLineChartActivity.this.startActivity(gotoIntent);
  			}
  			else
  			{  				
  				foodprices = operationResult.split(","); //此处可能因为中英文逗号的原因而出问题
  				LineGraphView graphView = new LineGraphView(
  						this
  						, city + "最近"+"天" + food+"的价格波动情况"
  				);
  				gvd = this.getData(city, food,foodprices);		
  				gvs = new GraphViewSeries(gvd);		
  				graphView.addSeries(gvs);		
  				setContentView(graphView);
  			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
	}
	
	//获得对应城市、食物在对应时间段的价格变化情况，返回GraphViewData[]
	public GraphViewData[] getData(String city, String food,String[] prices)
	{		
		 GraphViewData[] result	 = new GraphViewData[]
	     {
				new GraphViewData(1,Double.parseDouble(prices[0])),
				new GraphViewData(2,Double.parseDouble(prices[1])),
				new GraphViewData(3,Double.parseDouble(prices[2])),
				new GraphViewData(4,Double.parseDouble(prices[3])),
				new GraphViewData(5,Double.parseDouble(prices[4]))
	     };		 
		 return result;
	}
	
	public void DisplayToast(String str,int time)   
    {  
    	toast = Toast.makeText(this, str, time);       
    	//设置toast显示的位置             	
    	toast.setGravity(Gravity.TOP, 0, 320);         
    	//显示该Toast       	
    	toast.show();    	
    }
	
}
